package com.tbit.uqbike.service.business.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tbit.uqbike.enums.SystemCodeEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.Machine;
import com.tbit.uqbike.object.pojo.MachineBatteryModel;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.ErrorDataList;
import com.tbit.uqbike.service.base.MachineService;
import com.tbit.uqbike.service.business.AccountService;
import com.tbit.uqbike.service.business.MachineBatteryModelService;
import com.tbit.uqbike.webmanager.business.machinegroup.dao.core.MachineGroupDao;
import com.tbit.uqbike.webmanager.business.machinegroup.object.MachineGroup;
import com.tbit.uqbike.webmanager.business.userdivide.dao.core.UserDivideDao;
import com.tbit.uqbike.webmanager.business.userdivide.object.SubAccountRatio;
import com.tbit.uqbike.webmanager.dao.core.MachineBatteryModelDao;
import com.tbit.uqbike.webmanager.dao.core.MachineDao;
import com.tbit.uqbike.webmanager.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenmengran
 * @Description: 电池方案绑定
 * @date 2019\12\24 002415:25
 */
@Service
public class MachineBatteryModelServiceImpl implements MachineBatteryModelService {
    @Autowired
    private MachineService machineService;
    @Autowired
    private MachineBatteryModelDao machineBatteryModelDao;
    @Autowired
    private AccountService accountService;
    @Autowired
    private MachineDao machineDao;
    @Autowired
    private UserDivideDao userDivideDao;
    @Autowired
    private MachineGroupDao machineGroupDao;

    @Override
    public List<ErrorDataList> bound(LoginInfo loginInfo, Integer accountId, Integer batteryModelId, Integer secondaryBattertId, List<String> machineNOList, Integer machineGroupId) {
        List<ErrorDataList> errorDataLists = new ArrayList<ErrorDataList>();
        /**异常设备**/
        List<String> notExistMachineNOs = new ArrayList<String>();//不存在设备
        List<String> notAuthMachineNOs = new ArrayList<String>();//无权操作设备
        /**查询不存在的设备*/
        List<Machine> machineExist = machineService.getByMachineNOs(machineNOList);
        Map<String, String> machineNOExistMap = new HashMap<String, String>();
        for (Machine machine : machineExist) {
            machineNOExistMap.put(machine.getMachineNO(), machine.getMachineNO());
        }
        for (String machineNO : machineNOList) {
            if (!machineNOExistMap.containsKey(machineNO)) {
                notExistMachineNOs.add(machineNO);
            }
        }
        List<Integer> accountIds = accountService.getAllOperateAccountId(loginInfo);
        /**查询设备*/
        List<Machine> machines = machineService.getByAccountIdAndMachineNOs(accountIds, machineNOList);

        // 校验车辆分组
        if (machineGroupId != null && machineGroupId != -1) {
            if (!machineGroupDao.exists(
                    Wrappers.<MachineGroup>lambdaQuery()
                            .eq(MachineGroup::getMachineGroupId, machineGroupId))
            ) {
                throw new BaseException("分组不存在");
            }

            if (!userDivideDao.exists(Wrappers.<SubAccountRatio>lambdaQuery()
                    .eq(SubAccountRatio::getMachineGroupId, machineGroupId))) {
                throw new BaseException("该分组未设置分组比例，不允许添加车辆");
            }
            MachineGroup group = machineGroupDao.selectById(machineGroupId);
            if (!group.getAccountId().equals(accountId)) {
                throw new BaseException("分组不属于当前所选区域");
            }
        }
        if (machines.stream().anyMatch(m -> !m.getAccountId().equals(accountId))) {
            throw new BaseException("设备不属于当前所选区域");
        }

        List<Integer> machineIds = new ArrayList<>();
        /**无权操作的设备*/
        Map<String, String> machineNOAuchMap = new HashMap<>();
        for (Machine machine : machines) {
            machineIds.add(machine.getMachineId());
            machineNOAuchMap.put(machine.getMachineNO(), machine.getMachineNO());
        }
        for (String machineNO : machineNOList) {
            if (!machineNOAuchMap.containsKey(machineNO) && machineNOExistMap.containsKey(machineNO)) {
                notAuthMachineNOs.add(machineNO);
            }
        }
        if (machineIds.size() > 0) {
            if (batteryModelId != null) {
                /**删除旧的绑定*/
                delBatch(machineIds);
                /**添加新的绑定*/
                List<MachineBatteryModel> machineBatteryModels = new ArrayList<MachineBatteryModel>();
                for (Integer machineId : machineIds) {
                    MachineBatteryModel machineBatteryModel1 = new MachineBatteryModel();
                    machineBatteryModel1.setBatteryModelId(batteryModelId);
                    machineBatteryModel1.setMachineId(machineId);
                    machineBatteryModel1.setSecondaryBattertId(secondaryBattertId);
                    machineBatteryModels.add(machineBatteryModel1);
                }
                addBatch(machineBatteryModels);
            }

            // 绑定车辆分组
            if (machineGroupId != null) {
                if (machineGroupId == -1) { // 无分组
                    machineGroupId = null;
                }
                machineDao.updateGroup(machineIds, machineGroupId);
            }
        }
        /**封装错误信息*/
        if (notExistMachineNOs.size() > 0) {
            errorDataLists.add(new ErrorDataList("1", "设备编号不存在", notExistMachineNOs));
        }
        if (notAuthMachineNOs.size() > 0) {
            errorDataLists.add(new ErrorDataList("2", "无权操作", notAuthMachineNOs));
        }

        return errorDataLists;
    }


    @Override
    public List<ErrorDataList> boundNew(LoginInfo loginInfo, Integer batteryModelId, Integer secondaryBattertId, List<String> machineNOList,int dataType) {
        List<ErrorDataList> errorDataLists = new ArrayList<ErrorDataList>();
        /**异常设备**/
        List<String> notExistMachineNOs = new ArrayList<String>();//不存在设备
        List<String> notAuthMachineNOs = new ArrayList<String>();//无权操作设备
        /**查询不存在的设备*/
        List<Machine> machineExist = null;
        //0是设备编号,1是用户编号
        if (dataType == 0){
            machineExist = machineService.getByMachineNOs(machineNOList);
        }else {
            machineExist = machineService.getByUserCodes(machineNOList);
        }

        Map<String, String> machineNOExistMap = new HashMap<String, String>();
        for (Machine machine : machineExist) {
            if (dataType == 0){
                machineNOExistMap.put(machine.getMachineNO(), machine.getMachineNO());
            }else {
                machineNOExistMap.put(machine.getUserCode(), machine.getMachineNO());
            }
        }
        for (String machineNO : machineNOList) {
            if (!machineNOExistMap.containsKey(machineNO)) {
                notExistMachineNOs.add(machineNO);
            }
        }
        List<Integer> accountIds = accountService.getAllOperateAccountId(loginInfo);
        /**查询设备*/
        List<Machine> machines = machineService.getByAccountIdAndMachineNOs(accountIds, machineNOList);
        List<Integer> machineIds = new ArrayList<>();
        /**无权操作的设备*/
        Map<String, String> machineNOAuchMap = new HashMap<>();
        for (Machine machine : machines) {
            machineIds.add(machine.getMachineId());
            machineNOAuchMap.put(machine.getMachineNO(), machine.getMachineNO());
        }
        for (String machineNO : machineNOList) {
            if (!machineNOAuchMap.containsKey(machineNO) && machineNOExistMap.containsKey(machineNO)) {
                notAuthMachineNOs.add(machineNO);
            }
        }
        if (machineIds.size() > 0) {
            /**删除旧的绑定*/
            delBatch(machineIds);
            /**添加新的绑定*/
            List<MachineBatteryModel> machineBatteryModels = new ArrayList<MachineBatteryModel>();
            for (Integer machineId : machineIds) {
                MachineBatteryModel machineBatteryModel1 = new MachineBatteryModel();
                machineBatteryModel1.setBatteryModelId(batteryModelId);
                machineBatteryModel1.setMachineId(machineId);
                machineBatteryModel1.setSecondaryBattertId(secondaryBattertId);
                machineBatteryModels.add(machineBatteryModel1);
            }
            addBatch(machineBatteryModels);
        }
        machineNOList.removeAll(notExistMachineNOs);
        machineNOList.removeAll(notAuthMachineNOs);
        if (machineNOList.size() > 0){
            errorDataLists.add(new ErrorDataList("3", dataType == 0?"设备编号":"用户编号"+"成功", machineNOList));
        }
        /**封装错误信息*/
        if (notExistMachineNOs.size() > 0) {
            errorDataLists.add(new ErrorDataList("1", dataType == 0?"设备编号":"用户编号"+"不存在", notExistMachineNOs));
        }
        if (notAuthMachineNOs.size() > 0) {
            errorDataLists.add(new ErrorDataList("2", "无权操作", notAuthMachineNOs));
        }
        return errorDataLists;
    }


    @Override
    public void addBatch(List<MachineBatteryModel> machineBatteryModels) {
        machineBatteryModelDao.addBatch(machineBatteryModels);
    }

    @Override
    public void delBatch(List<Integer> machineIds) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("machineIds", StringUtil.getListString(machineIds));

        machineBatteryModelDao.delBatch(params);
    }

    @Override
    public MachineBatteryModel getByMachineNO(LoginInfo loginInfo, String machineNO) {
        //权限验证
        List<Integer> accountIds = accountService.getAllOperateAccountId(loginInfo);

        Machine machine = machineService.getByMachineNO(machineNO);
        if (machine == null) {
            throw new BaseException(SystemCodeEnum.MACHINE_NOT_EXIST);
        }

        if (accountIds == null
                || accountIds.size() < 1
                || !accountIds.contains(machine.getAccountId())) {
            throw new BaseException(SystemCodeEnum.NO_PRIVILEGE);
        }

        return machineBatteryModelDao.getByMachineId(machine.getMachineId());
    }

    @Override
    public List<MachineBatteryModel> getByBatteryModelId(LoginInfo loginInfo, Integer
            batteryModelId, Integer rowCount, Integer pageNO) {
        //权限验证
        List<Integer> accountIds = accountService.getAllOperateAccountId(loginInfo);
        Map<String, Object> params = new HashMap<>();
        params.put("accountIds", accountIds);
        params.put("batteryModelId", batteryModelId);
        params.put("pageSize", (pageNO - 1) * rowCount);
        params.put("rowCount", rowCount);

        return machineBatteryModelDao.getByBatteryModelId(params);
    }

    @Override
    public Integer getTotalByBatteryModelId(LoginInfo loginInfo, Integer batteryModelId) {
        List<Integer> accountIds = accountService.getAllOperateAccountId(loginInfo);
        Map<String, Object> params = new HashMap<>();
        params.put("accountIds", accountIds);
        params.put("batteryModelId", batteryModelId);

        return machineBatteryModelDao.getTotalByBatteryModelId(params);
    }


}
